﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Assist;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.UI;
using FlexCell;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.ProgressBar;
using YArchitech.Revit;
using YJKRevitBase.WinForm;
using YJKRevitCurveDrag;
using YJKMaterialStatistic;
using YJKExcelFormTool;
using YJKExcelFormTool.Designer;
using YJKPresentation.Utils;

namespace YJKExcelTableUtil
{
	public class GridToolExportImportRevit
	{
		public GridToolExportImportRevit(ExternalCommandData cmdData, XYZ ptPos)
		{
			this.m_cmdData = cmdData;
			this.m_doc = cmdData.Application.ActiveUIDocument.Document;
			this.m_ptPos = ptPos;
			this.GetXYDpi(ref this.m_dpiX, ref this.m_dpiY);
			this.m_nVersionNumber = Convert.ToInt32(this.m_cmdData.Application.Application.VersionNumber);
		}

        public GridToolExportImportRevit(ExternalCommandData cmdData, FlexCell.Grid grid, string gridName = "", int lineWidthOut = 7, int lineWidthInner = 2, CREATENEWVIEW newView = CREATENEWVIEW.NONE)
		{
			this.m_cmdData = cmdData;
			this.m_doc = cmdData.Application.ActiveUIDocument.Document;
			this.m_grid = grid;
			this.m_LineWidthOut = lineWidthOut;
			this.m_LineWidthInner = lineWidthInner;
			this.m_IfCreateNewView = newView;
			this.m_GridName = gridName;
			this.GetXYDpi(ref this.m_dpiX, ref this.m_dpiY);
			this.m_nVersionNumber = Convert.ToInt32(this.m_cmdData.Application.Application.VersionNumber);
		}

        public bool SetGrid(ExternalCommandData cmdData, FlexCell.Grid grid, CREATENEWVIEW newView = CREATENEWVIEW.NONE)
		{
			if (grid == null)
			{
				return false;
			}
			this.m_doc = cmdData.Application.ActiveUIDocument.Document;
			this.m_grid = grid;
			this.m_IfCreateNewView = newView;
			this.GetXYDpi(ref this.m_dpiX, ref this.m_dpiY);
			return true;
		}

		private void GetXYDpi(ref double Xdpi, ref double Ydpi)
		{
			using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
			{
				Xdpi = (double)graphics.DpiX;
				Ydpi = (double)graphics.DpiY;
			}
		}

		private void GetGridRealRowCol(ref int RowFirst, ref int RowLast, ref int ColFirst, ref int ColLast)
		{
			if (this.m_grid == null)
			{
				return;
			}
			for (int i = 1; i < this.m_grid.Rows; i++)
			{
				for (int j = 1; j < this.m_grid.Cols; j++)
				{
					if (this.m_grid.Column(j).Visible)
					{
						Cell cell = this.m_grid.Cell(i, j);
						if (cell.Text != "" || cell.ImageKey != "" || cell.BackColor != System.Drawing.Color.White || this.CellHasBorder(cell))
						{
							if (cell.MergeCell)
							{
								Range range = this.m_grid.Range(i, j, i, j);
								if (RowFirst == 0)
								{
									RowFirst = range.FirstRow;
									RowLast = range.LastRow;
								}
								else if (RowLast == 0 || range.LastRow > RowLast)
								{
									RowLast = range.LastRow;
								}
								if (ColFirst == 0)
								{
									ColFirst = range.FirstCol;
									ColLast = range.LastCol;
								}
								else if (ColLast == 0 || range.LastCol > ColLast)
								{
									ColLast = range.LastCol;
								}
							}
							else
							{
								if (RowFirst == 0)
								{
									RowFirst = i;
								}
								else if (RowLast == 0 || i > RowLast)
								{
									RowLast = i;
								}
								if (ColFirst == 0)
								{
									ColFirst = j;
								}
								else
								{
									if (ColLast == 0 || j > ColLast)
									{
										ColLast = j;
									}
									if (j < ColFirst)
									{
										ColFirst = j;
									}
								}
							}
						}
					}
				}
			}
			if (RowLast == 0)
			{
				RowLast = RowFirst;
			}
			if (ColLast == 0)
			{
				ColLast = ColFirst;
			}
		}

		private bool CellHasBorder(Cell cell)
		{
			return cell.get_Border(EdgeEnum.Left) != LineStyleEnum.None || cell.get_Border(EdgeEnum.Right) != LineStyleEnum.None || cell.get_Border(EdgeEnum.Top) != LineStyleEnum.None || cell.get_Border(EdgeEnum.Bottom) != LineStyleEnum.None || cell.get_Border(EdgeEnum.DiagonalDown) != LineStyleEnum.None || cell.get_Border(EdgeEnum.DiagonalUp) != LineStyleEnum.None;
		}

		private bool GetGridDrawInfo()
		{
			if (this.m_GridLineInfoH == null || this.m_GridLineInfoV == null)
			{
				return false;
			}
			List<Range> list = new List<Range>();
			XYZ xyz = this.m_ptBase;
			XYZ xyz2 = this.m_ptBase;
			XYZ xyz3 = this.m_ptBase;
			if (GridToolExportImportRevit._hWndRevit == null)
			{
                GridToolExportImportRevit._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			ProgressBarForm progressBarForm = new ProgressBarForm(this.m_grid.Rows - 1, "正在绘制表格", ProgressBarStyle.Blocks, true, false);
			progressBarForm.Show(GridToolExportImportRevit._hWndRevit);
			if (this.m_nVersionNumber > 2016 && !this.m_bIsSplitTable)
			{
				this.ModifyCell();
			}
			for (int i = 1; i < this.m_grid.Rows; i++)
			{
				progressBarForm.RefreshProgressBar();
				if (progressBarForm.m_stopTag)
				{
					return false;
				}
				this.m_RowHeightEx.Add(this.m_grid.Row(i).Height);
				double num = this.UnitTransform(this.m_grid.Row(i).Height) * this.GRID_SCALE;
				xyz -= XYZ.BasisY * num;
				xyz2 = xyz;
				xyz3 = xyz2;
				for (int j = 1; j < this.m_grid.Cols; j++)
				{
					if (this.m_grid.Column(j).Visible)
					{
						num = this.UnitTransform(this.m_grid.Row(i).Height) * this.GRID_SCALE;
						CellExtendedData cellExtendedData = new CellExtendedData();
						if (i == 1)
						{
							this.m_ColWidthEx.Add(this.m_grid.Column(j).Width);
						}
						double num2 = this.UnitTransform(this.m_grid.Column(j).Width) * this.GRID_SCALE;
						xyz3 = xyz2;
						if (i == 1)
						{
							GridLineInfo gridLineInfo = new GridLineInfo(true, num2);
							this.m_GridLineInfoH[0, j - 1] = gridLineInfo;
						}
						if (j == 1)
						{
							GridLineInfo gridLineInfo2 = new GridLineInfo(true, num);
							this.m_GridLineInfoV[i - 1, 0] = gridLineInfo2;
						}
						Cell cell = this.m_grid.Cell(i, j);
						if (cell.MergeCell)
						{
							Range range = this.m_grid.Range(i, j, i, j);
							cellExtendedData.FirstRow = range.FirstRow;
							cellExtendedData.FirstCol = range.FirstCol;
							cellExtendedData.LastRow = range.LastRow;
							cellExtendedData.LastCol = range.LastCol;
							if (this.IfRangeExist(list, range))
							{
								if (j == range.FirstCol)
								{
									for (int k = range.FirstCol; k <= range.LastCol; k++)
									{
										xyz2 += XYZ.BasisX * this.UnitTransform(this.m_grid.Column(k).Width) * this.GRID_SCALE;
									}
									goto IL_62B;
								}
								goto IL_62B;
							}
							else
							{
								list.Add(range);
								num = 0.0;
								num2 = 0.0;
								for (int l = range.FirstRow; l <= range.LastRow; l++)
								{
									double num3 = this.UnitTransform(this.m_grid.Row(l).Height) * this.GRID_SCALE;
									num += num3;
									num2 = 0.0;
									if (l != range.FirstRow)
									{
										xyz3 -= XYZ.BasisY * num3;
									}
									for (int m = range.FirstCol; m <= range.LastCol; m++)
									{
										double num4 = this.UnitTransform(this.m_grid.Column(m).Width) * this.GRID_SCALE;
										num2 += num4;
										if (l != range.LastRow)
										{
											GridLineInfo gridLineInfo3 = new GridLineInfo(false, num4);
											this.m_GridLineInfoH[l, m - 1] = gridLineInfo3;
										}
										else
										{
											GridLineInfo gridLineInfo4 = new GridLineInfo(true, num4);
											this.m_GridLineInfoH[l, m - 1] = gridLineInfo4;
										}
										if (m != range.LastCol)
										{
											GridLineInfo gridLineInfo5 = new GridLineInfo(false, num3);
											this.m_GridLineInfoV[l - 1, m] = gridLineInfo5;
										}
										else
										{
											GridLineInfo gridLineInfo6 = new GridLineInfo(true, num3);
											this.m_GridLineInfoV[l - 1, m] = gridLineInfo6;
										}
									}
								}
							}
						}
						else
						{
							GridLineInfo gridLineInfo7 = new GridLineInfo(true, num2);
							this.m_GridLineInfoH[i, j - 1] = gridLineInfo7;
							GridLineInfo gridLineInfo8 = new GridLineInfo(true, num);
							this.m_GridLineInfoV[i - 1, j] = gridLineInfo8;
							cellExtendedData.FirstRow = i;
							cellExtendedData.LastRow = i;
							cellExtendedData.FirstCol = j;
							cellExtendedData.LastCol = j;
						}
						this.GetCellDiagonal(cell, xyz2, num2, num);
						this.SetCellBorderDataEx(cell, ref cellExtendedData);
						string imageKey = cell.ImageKey;
						if (imageKey != "")
						{
							XYZ xyz4 = xyz3 + XYZ.BasisX * num2 * 0.5;
							xyz4 += XYZ.BasisY * num * 0.5;
							FlexCell.Image image = this.m_grid.Images.Item(imageKey);
							double imgWidth = this.UnitTransform((float)image.Picture.Width) * this.GRID_SCALE;
							double imgHeight = this.UnitTransform((float)image.Picture.Height) * this.GRID_SCALE;
							this.GetImageSize(image, cell.Alignment, num2, num, ref imgWidth, ref imgHeight);
							this.m_GridImage.Add(new GridImgInfo(imageKey, xyz4, imgWidth, imgHeight, i, j));
						}
						string text = cell.Text;
						if (text != "")
						{
							TextNoteType textNoteType = null;
							this.GetTextNoteType(ref textNoteType, cell);
							if (textNoteType != null)
							{
								XYZ baseVec;
								XYZ upVec;
								if (cell.Orientation == TextOrientationEnum.Horizontal)
								{
									baseVec = XYZ.BasisX;
									upVec = XYZ.BasisY;
								}
								else
								{
									baseVec = XYZ.BasisY;
									upVec = XYZ.BasisZ;
								}
								TextAlignFlags textAlign = 0;
								double lineWidth = num2 * this.TEXT_SCALE;
								this.GetTextPosition(ref xyz3, ref textAlign, num, num2, cell);
								JigTextInfo jigTxtInfo = new JigTextInfo(textNoteType, xyz3, baseVec, upVec, textAlign, lineWidth, text);
								this.m_GridText.Add(new JigTextInfoEx(jigTxtInfo, i, j));
							}
						}
						xyz2 += XYZ.BasisX * num2;
						this.m_CellExtendInfo.Add(cellExtendedData);
					}
					IL_62B:;
				}
			}
			return true;
		}

		private bool ModifyCell()
		{
			string strXmlPath = Product.InstallLocation + "\\Data\\文字.xml";
			XmlNode xnRoot = null;
			if (!TextCalculation.LoadXml(strXmlPath, ref xnRoot))
			{
				return false;
			}
			this.AddRowHigh(xnRoot);
			this.AddColHigh();
			return true;
		}

		private void AddRowHigh(XmlNode xnRoot)
		{
			TextData textData = new TextData();
			TextData textData2 = new TextData();
			for (int i = 1; i < this.m_grid.Rows; i++)
			{
				int num = 0;
				short num2 = 0;
				for (int j = 1; j < this.m_grid.Cols; j++)
				{
					Cell cell = this.m_grid.Cell(i, j);
					float num3 = cell.FontSize;
					num3 = (float)Math.Round((double)num3, MidpointRounding.AwayFromZero);
					if (textData.FontName != cell.FontName || textData.FontSize != (double)num3)
					{
						textData.FontName = cell.FontName;
						textData.FontSize = (double)num3;
						TextCalculation.ReadXmlData(xnRoot, "非汉字", ref textData);
					}
					if (textData2.FontName != cell.FontName || textData2.FontSize != (double)num3)
					{
						textData2.FontName = cell.FontName;
						textData2.FontSize = (double)num3;
						TextCalculation.ReadXmlData(xnRoot, "汉字", ref textData2);
					}
					int textRowsAndSize = this.GetTextRowsAndSize(cell, textData, textData2);
					short num4 = (short)((int)this.CalculationRowHigh(textData.FontName, textData.FontSize) * textRowsAndSize);
					if (num2 < num4)
					{
						num2 = num4;
					}
					if (num < textRowsAndSize)
					{
						num = textRowsAndSize;
					}
				}
				if (Geometry.LessThan((double)this.m_grid.Row(i).Height, (double)num2))
				{
					this.m_dicRowHigh.Add(i, num2);
				}
			}
			foreach (KeyValuePair<int, short> keyValuePair in this.m_dicRowHigh)
			{
				this.m_grid.Row(keyValuePair.Key).Height = keyValuePair.Value;
			}
		}

		private void AddColHigh()
		{
			for (int i = 1; i < this.m_grid.Cols; i++)
			{
				short num = 0;
				for (int j = 1; j < this.m_grid.Rows; j++)
				{
					Cell cell = this.m_grid.Cell(j, i);
					double nTextLengh = this.FindSingleRowTextSize(cell);
					Range range = this.m_grid.Range(j, i, j, i);
					short num2 = this.HandleMergeCell(range, nTextLengh, i);
					if (num < num2)
					{
						num = num2;
					}
				}
				if (this.m_grid.Column(i).Width < num)
				{
					this.m_dicColWidth.Add(i, num);
				}
			}
			foreach (KeyValuePair<int, short> keyValuePair in this.m_dicColWidth)
			{
				this.m_grid.Column(keyValuePair.Key).Width = keyValuePair.Value;
			}
		}

		private short HandleMergeCell(Range range, double nTextLengh, int nIndex)
		{
			double num = 0.0;
			for (int i = range.FirstCol; i < range.LastCol + 1; i++)
			{
				num += (double)this.m_grid.Column(i).Width;
			}
			return (short)Math.Ceiling((double)this.m_grid.Column(nIndex).Width / num * nTextLengh);
		}

		private int GetTextRowsAndSize(Cell cell, TextData textDataEOrN, TextData textDataC)
		{
			int num = 0;
			double value = 0.0;
			short num2 = 0;
			string text = cell.Text;
			if (cell.MergeCell)
			{
				Range range = this.m_grid.Range(cell.Row, cell.Col, cell.Row, cell.Col);
				int firstCol = range.FirstCol;
				int lastCol = range.LastCol;
				for (int i = firstCol; i <= lastCol; i++)
				{
					num2 += this.m_grid.Column(i).Width;
				}
			}
			else
			{
				num2 = this.m_grid.Column(cell.Col).Width;
			}
			string[] separator = new string[]
			{
				"\r\n"
			};
			string[] strSubArry = text.Split(separator, StringSplitOptions.None);
			this.GetTextRowsAndSize(cell, strSubArry, num2, textDataEOrN, textDataC, ref value, ref num);
			if (!this.m_dicOneRowTextNumbers.ContainsKey(cell))
			{
				this.m_dicOneRowTextNumbers.Add(cell, value);
			}
			if (!this.m_dicRowNumbers.ContainsKey(cell))
			{
				this.m_dicRowNumbers.Add(cell, num);
			}
			return num;
		}

		private void GetTextRowsAndSize(Cell cell, string[] strSubArry, short dCellWidthPx, TextData textDataEOrN, TextData textDataC, ref double sTextLengh, ref int nRow)
		{
			foreach (string s in strSubArry)
			{
				byte[] bytes = new ASCIIEncoding().GetBytes(s);
				if (bytes.Length != 0)
				{
					double num = 0.0;
					List<int> list = new List<int>();
					double num2;
					for (int j = 0; j <= bytes.Length - 1; j++)
					{
						list.Add((int)bytes[j]);
						double cellWitdh;
						if (bytes[j] == 63)
						{
							cellWitdh = textDataC.CellWitdh;
						}
						else
						{
							cellWitdh = textDataEOrN.CellWitdh;
						}
						num += cellWitdh;
						if (num + 5.0 > (double)dCellWidthPx)
						{
							list.Remove((int)bytes[j]);
							num2 = TextCalculation.TextWidthCalculation(list, textDataEOrN, textDataC);
							list.Clear();
							list.Add((int)bytes[j]);
							nRow++;
							if (Geometry.Lessthan_Or_Equal(num2, (double)dCellWidthPx))
							{
								sTextLengh = (double)dCellWidthPx;
							}
							else if (sTextLengh < num2)
							{
								sTextLengh = num2;
							}
							num = cellWitdh;
						}
						else if (num + 5.0 == (double)dCellWidthPx)
						{
							num2 = TextCalculation.TextWidthCalculation(list, textDataEOrN, textDataC);
							list.Clear();
							nRow++;
							if (Geometry.Lessthan_Or_Equal(num2, (double)dCellWidthPx))
							{
								sTextLengh = (double)dCellWidthPx;
							}
							else if (sTextLengh < num2)
							{
								sTextLengh = num2;
							}
							num = 0.0;
						}
					}
					num2 = TextCalculation.TextWidthCalculation(list, textDataEOrN, textDataC);
					if (sTextLengh < num2)
					{
						sTextLengh = num2;
					}
					if (!Geometry.Lessthan_Or_Equal(num, 0.0))
					{
						nRow++;
					}
				}
			}
			if (Geometry.Lessthan_Or_Equal(sTextLengh, (double)dCellWidthPx))
			{
				sTextLengh = (double)dCellWidthPx;
			}
		}

		private int FindRowNumbers(Cell cell)
		{
			int result = 0;
			foreach (KeyValuePair<Cell, int> keyValuePair in this.m_dicRowNumbers)
			{
				if (cell.Row == keyValuePair.Key.Row && cell.Col == keyValuePair.Key.Col)
				{
					result = keyValuePair.Value;
					break;
				}
			}
			return result;
		}

		private double FindSingleRowTextSize(Cell cell)
		{
			double result = 0.0;
			foreach (KeyValuePair<Cell, double> keyValuePair in this.m_dicOneRowTextNumbers)
			{
				if (cell.Row == keyValuePair.Key.Row && cell.Col == keyValuePair.Key.Col)
				{
					result = keyValuePair.Value;
					break;
				}
				if (keyValuePair.Key.MergeCell)
				{
					Range range = this.m_grid.Range(keyValuePair.Key.Row, keyValuePair.Key.Col, keyValuePair.Key.Row, keyValuePair.Key.Col);
					int firstRow = range.FirstRow;
					int lastRow = range.LastRow;
					int firstCol = range.FirstCol;
					int lastCol = range.LastCol;
					if (cell.Row >= firstRow && cell.Row <= lastRow && cell.Col >= firstCol && cell.Col <= lastCol)
					{
						result = keyValuePair.Value;
						break;
					}
				}
			}
			return result;
		}

		private void GetTextNotePosition(ref XYZ pt, TextAlignFlags txtAlign, double dCellHeight, double dCellWidth, double txtHeight, double scale, int nTxtRows, double dOffset)
		{
            if ((int)txtAlign <= 1088)
			{
                if ((int)txtAlign <= 640)
				{
                    if ((int)txtAlign == 576)
					{
						pt += XYZ.BasisY * dCellHeight;
						pt += XYZ.BasisY * dOffset * scale;
						return;
					}
                    if ((int)txtAlign == 640)
					{
						pt += XYZ.BasisX * 0.5 * dCellWidth;
						pt += XYZ.BasisY * dCellHeight;
						pt += XYZ.BasisY * dOffset * scale;
						return;
					}
				}
				else
				{
                    if ((int)txtAlign == 768)
					{
						pt += XYZ.BasisX * dCellWidth;
						pt += XYZ.BasisY * dCellHeight;
						pt += XYZ.BasisY * dOffset * scale;
						return;
					}
                    if ((int)txtAlign == 1088)
					{
						pt += XYZ.BasisY * txtHeight;
						pt += XYZ.BasisY * (dCellHeight - txtHeight) / 2.0;
						return;
					}
				}
			}
            else if ((int)txtAlign <= 1280)
			{
                if ((int)txtAlign == 1152)
				{
					pt += XYZ.BasisX * 0.5 * dCellWidth;
					pt += XYZ.BasisY * txtHeight;
					pt += XYZ.BasisY * (dCellHeight - txtHeight) / 2.0;
					return;
				}
                if ((int)txtAlign == 1280)
				{
					pt += XYZ.BasisX * dCellWidth;
					pt += XYZ.BasisY * txtHeight;
					pt += XYZ.BasisY * (dCellHeight - txtHeight) / 2.0;
					return;
				}
			}
			else
			{
                if ((int)txtAlign == 2112)
				{
					pt += XYZ.BasisY * txtHeight;
					return;
				}
                if ((int)txtAlign == 2176)
				{
					pt += XYZ.BasisX * 0.5 * dCellWidth;
					pt += XYZ.BasisY * txtHeight;
					return;
				}
                if ((int)txtAlign == 2304)
				{
					pt += XYZ.BasisX * dCellWidth;
					pt += XYZ.BasisY * txtHeight;
					return;
				}
			}
			pt += XYZ.BasisY * dCellHeight;
			pt += XYZ.BasisX * dOffset * scale;
			pt -= XYZ.BasisY * dOffset * scale;
		}

		private short CalculationRowHigh(string strFontName, double fontSize)
		{
			short result = 0;
			if (this.m_nVersionNumber == 2017 || this.m_nVersionNumber == 2018)
			{
				if (strFontName == "宋体" || strFontName == "黑体" || strFontName == "楷体")
				{
					result = (short)Math.Ceiling(fontSize * 13.0 / 6.0);
				}
				else if (strFontName == "微软雅黑")
				{
					result = (short)Math.Ceiling(fontSize * 2.5);
				}
				else if (strFontName == "仿宋")
				{
					result = (short)Math.Ceiling(fontSize * 9.0 / 4.0);
				}
				else if (strFontName == "RomanD")
				{
					result = (short)Math.Ceiling(fontSize * 2.0);
				}
			}
			else if (this.m_nVersionNumber == 2019)
			{
				if (strFontName == "宋体" || strFontName == "黑体" || strFontName == "楷体" || strFontName == "仿宋")
				{
					result = (short)Math.Ceiling(fontSize * 5.0 / 3.0);
				}
				else if (strFontName == "微软雅黑")
				{
					result = (short)Math.Ceiling(fontSize * 4.0 / 3.0);
				}
				else if (strFontName == "RomanD")
				{
					result = (short)Math.Ceiling(fontSize * 2.0);
				}
			}
			return result;
		}

		private void GetTextPosition(ref XYZ pt, ref TextAlignFlags txtAlign, double dCellHeight, double dCellWidth, Cell cell)
		{
			AlignmentEnum alignment = cell.Alignment;
			double num = (double)(cell.FontSize / 72f / 13f) * this.GRID_SCALE;
			int num2;
			if (this.m_nVersionNumber > 2016 && !this.m_bIsSplitTable)
			{
				num2 = this.FindRowNumbers(cell);
			}
			else
			{
				num2 = this.GetTextRows(cell);
			}
			num *= (double)num2;
			switch (alignment)
			{
			case AlignmentEnum.LeftTop:
            txtAlign = (TextAlignFlags)576;
				goto IL_E2;
			case AlignmentEnum.LeftCenter:
                txtAlign = (TextAlignFlags)1088;
				goto IL_E2;
			case AlignmentEnum.LeftBottom:
                txtAlign = (TextAlignFlags)2112;
				goto IL_E2;
			case AlignmentEnum.CenterTop:
                txtAlign = (TextAlignFlags)640;
				goto IL_E2;
			case AlignmentEnum.CenterCenter:
                txtAlign = (TextAlignFlags)1152;
				goto IL_E2;
			case AlignmentEnum.CenterBottom:
                txtAlign = (TextAlignFlags)2176;
				goto IL_E2;
			case AlignmentEnum.RightTop:
                txtAlign = (TextAlignFlags)768;
				goto IL_E2;
			case AlignmentEnum.RightCenter:
                txtAlign = (TextAlignFlags)1280;
				goto IL_E2;
			case AlignmentEnum.RightBottom:
                txtAlign = (TextAlignFlags)2304;
				goto IL_E2;
			}
            txtAlign = (TextAlignFlags)576;
			IL_E2:
			if (this.m_nVersionNumber > 2016)
			{
				double dOffset = 1.5 / this.m_dpiY * 0.08333;
				num = this.UnitTransform(this.CalculationRowHigh(cell.FontName, (double)cell.FontSize)) * (double)num2 * this.GRID_SCALE;
				this.GetTextNotePosition(ref pt, txtAlign, dCellHeight, dCellWidth, num, this.GRID_SCALE, num2, dOffset);
				return;
			}
			RevitElementExtension.GetTextNotePosition(ref pt, txtAlign, dCellHeight, dCellWidth, num, this.m_dpiY, this.GRID_SCALE);
		}

		private int GetTextRows(Cell cell)
		{
			int num;
			if (cell.WrapText)
			{
				string text = cell.Text;
				string[] separator = new string[]
				{
					"\r\n"
				};
				string[] array = text.Split(separator, StringSplitOptions.None);
				num = 0;
				float fontSize = cell.FontSize;
				double num2 = 0.0;
				if (cell.MergeCell)
				{
					Range range = this.m_grid.Range(cell.Row, cell.Col, cell.Row, cell.Col);
					int firstCol = range.FirstCol;
					int lastCol = range.LastCol;
					for (int i = firstCol; i <= lastCol; i++)
					{
						num2 += (double)this.m_grid.Column(i).Width;
					}
				}
				else
				{
					num2 = (double)this.m_grid.Column(cell.Col).Width;
				}
				foreach (string s in array)
				{
					byte[] bytes = new ASCIIEncoding().GetBytes(s);
					if (bytes.Length == 0)
					{
						num++;
					}
					else
					{
						int num3 = 0;
						for (int k = 0; k <= bytes.Length - 1; k++)
						{
							if (bytes[k] == 63)
							{
								num3++;
							}
							num3++;
						}
						double num4 = (double)num3 * 0.5 * (double)fontSize / 72.0 * this.m_dpiX;
						num += (int)Math.Ceiling(num4 / num2);
					}
				}
			}
			else
			{
				num = 1;
			}
			return num;
		}

		private void GetCellDiagonal(Cell cell, XYZ ptBaseH, double cellWidth, double cellHeight)
		{
			if (cell.get_Border(EdgeEnum.DiagonalUp) != LineStyleEnum.None)
			{
				this.m_GridLine.Add(new JigEdgeInfoEx(new JigEdgeInfo(ptBaseH, ptBaseH + XYZ.BasisX * cellWidth + XYZ.BasisY * cellHeight, 0.0), false));
			}
			if (cell.get_Border(EdgeEnum.DiagonalDown) != LineStyleEnum.None)
			{
				this.m_GridLine.Add(new JigEdgeInfoEx(new JigEdgeInfo(ptBaseH + XYZ.BasisY * cellHeight, ptBaseH + XYZ.BasisX * cellWidth, 0.0), false));
			}
		}

		private int ParseRGB(System.Drawing.Color color)
		{
			return (int)color.B << 16 | (int)((ushort)((int)color.G << 8 | (int)color.R));
		}

		private void GetTextNoteType(ref TextNoteType txtNoteType, Cell cell)
		{
			string fontName = cell.FontName;
			int num = this.ParseRGB(cell.ForeColor);
            //RevitVersion.GetVersionNumber(this.m_doc) != "2016";
			double num2 = (double)(cell.FontSize / 72f / 14f);
			int num3 = cell.FontBold ? 1 : 0;
			int num4 = cell.FontItalic ? 1 : 0;
			int num5 = cell.FontUnderline ? 1 : 0;
			IEnumerable<Element> enumerable = new FilteredElementCollector(this.m_doc).OfClass(typeof(TextNoteType)).ToElements();
			TextNoteType textNoteType = null;
			foreach (Element element in enumerable)
			{
				TextNoteType textNoteType2 = element as TextNoteType;
				if (textNoteType2 != null)
				{
					textNoteType = textNoteType2;
					string a = textNoteType2.GetParameter(BuiltInParameter.TEXT_FONT).AsString();
					int num6 = textNoteType2.GetParameter(BuiltInParameter.LINE_COLOR).AsInteger();
					double val = textNoteType2.GetParameter(BuiltInParameter.TEXT_SIZE).AsDouble();
					int num7 = textNoteType2.GetParameter(BuiltInParameter.TEXT_STYLE_BOLD).AsInteger();
					int num8 = textNoteType2.GetParameter(BuiltInParameter.TEXT_STYLE_ITALIC).AsInteger();
					int num9 = textNoteType2.GetParameter(BuiltInParameter.TEXT_STYLE_UNDERLINE).AsInteger();
					if (a == fontName && Geometry.IsEqual(val, num2, 1E-05) && num6 == num && num3 == num7 && num4 == num8 && num5 == num9)
					{
						txtNoteType = textNoteType2;
						return;
					}
				}
			}
			string text = string.Concat(new string[]
			{
				"HY_",
				fontName,
				"_",
				AssistFunc.feetToMM(num2).ToString("0.0000"),
				"mm_"
			});
			if (num3 == 1)
			{
				text += "加粗";
			}
			if (num4 == 1)
			{
				text += "斜体";
			}
			if (num5 == 1)
			{
				text += "下划线";
			}
			text += num.ToString();
			Transaction transaction = new Transaction(this.m_doc);
			try
			{
				transaction.Start("new textnote type");
				txtNoteType = (textNoteType.Duplicate(text) as TextNoteType);
				txtNoteType.GetParameter(BuiltInParameter.TEXT_FONT).Set(fontName);
				txtNoteType.GetParameter(BuiltInParameter.LINE_COLOR).Set(num);
				txtNoteType.GetParameter(BuiltInParameter.TEXT_SIZE).Set(num2);
				txtNoteType.GetParameter(BuiltInParameter.LEADER_OFFSET_SHEET).Set(0);
				txtNoteType.GetParameter(BuiltInParameter.TEXT_STYLE_BOLD).Set(num3);
				txtNoteType.GetParameter(BuiltInParameter.TEXT_STYLE_ITALIC).Set(num4);
				txtNoteType.GetParameter(BuiltInParameter.TEXT_STYLE_UNDERLINE).Set(num5);
				txtNoteType.GetParameter(BuiltInParameter.TEXT_BACKGROUND).Set(1);
				txtNoteType.GetParameter(BuiltInParameter.TEXT_WIDTH_SCALE).Set(1);
				transaction.Commit();
			}
			catch (Exception)
			{
				transaction.RollBack();
			}
		}

		private bool IfRangeExist(List<Range> lstRange, Range range)
		{
			foreach (Range range2 in lstRange)
			{
				if (range2.FirstRow == range.FirstRow && range2.FirstCol == range.FirstCol && range2.LastRow == range.LastRow && range2.LastCol == range.LastCol)
				{
					return true;
				}
			}
			return false;
		}

		private void GetImageSize(FlexCell.Image image, AlignmentEnum cellAlign, double cellWidth, double cellHeight, ref double imgWidth, ref double imgHeight)
		{
			if (image == null)
			{
				return;
			}
			if (cellAlign != AlignmentEnum.CenterCenter)
			{
				imgWidth = cellWidth;
				imgHeight = cellHeight;
				return;
			}
			if (Geometry.GreaterThan(cellWidth, imgWidth) && Geometry.GreaterThan(cellHeight, imgHeight))
			{
				return;
			}
			if (Geometry.GreaterThan(cellWidth, cellHeight))
			{
				imgWidth = cellHeight * imgWidth / imgHeight;
				imgHeight = cellHeight;
				return;
			}
			imgHeight = cellWidth * imgHeight / imgWidth;
			imgWidth = cellWidth;
		}

		private bool GetLineStyle(ref GraphicsStyle gridStyleOut, ref GraphicsStyle gridStyleInner)
		{
			Category category = this.m_doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines);
			if (category == null)
			{
				return false;
			}
			string text = "GridLineOut" + string.Format(" {0}", this.m_LineWidthOut);
			string text2 = "GridLineInner" + string.Format(" {0}", this.m_LineWidthInner);
			if (!category.SubCategories.Contains(text))
			{
				if (!this.CreateLineStyle(this.m_LineWidthOut, text, ref category))
				{
					return false;
				}
			}
			else
			{
				Category category2 = category.SubCategories.get_Item(text);
				Transaction transaction = new Transaction(this.m_doc, "lineWidth");
				transaction.Start();
				category2.LineColor = this.m_GridLineColor;
				category2.SetLineWeight(this.m_LineWidthOut, (Autodesk.Revit.DB.GraphicsStyleType)1);
				transaction.Commit();
			}
			if (!category.SubCategories.Contains(text2))
			{
				if (!this.CreateLineStyle(this.m_LineWidthInner, text2, ref category))
				{
					return false;
				}
			}
			else
			{
				Category category3 = category.SubCategories.get_Item(text2);
				Transaction transaction2 = new Transaction(this.m_doc, "lineWidth");
				transaction2.Start();
				category3.LineColor = this.m_GridLineColor;
				category3.SetLineWeight(this.m_LineWidthInner, (Autodesk.Revit.DB.GraphicsStyleType)1);
				transaction2.Commit();
			}
			foreach (Element element in new FilteredElementCollector(this.m_doc).OfClass(typeof(GraphicsStyle)))
			{
				GraphicsStyle graphicsStyle = element as GraphicsStyle;
				if (graphicsStyle != null)
				{
					if (graphicsStyle.Name.CompareTo(text) == 0)
					{
						gridStyleOut = graphicsStyle;
					}
					if (graphicsStyle.Name.CompareTo(text2) == 0)
					{
						gridStyleInner = graphicsStyle;
					}
				}
			}
			return gridStyleOut != null && gridStyleInner != null;
		}

		private bool CreateLineStyle(int lineWidth, string typeName, ref Category lineCategory)
		{
			Transaction transaction = new Transaction(this.m_doc);
			bool result;
			try
			{
				transaction.Start("new line style");
				Category category = this.m_doc.Settings.Categories.NewSubcategory(lineCategory, typeName);
				if (typeName.IndexOf("GridLineOut") != -1)
				{
					category.LineColor = this.m_GridLineColor;
					category.SetLineWeight(this.m_LineWidthOut, (Autodesk.Revit.DB.GraphicsStyleType)1);
				}
				else
				{
					category.LineColor = this.m_GridLineColor;
					category.SetLineWeight(this.m_LineWidthInner, (Autodesk.Revit.DB.GraphicsStyleType)1);
				}
				transaction.Commit();
				result = true;
			}
			catch (Exception)
			{
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				result = false;
			}
			return result;
		}

		public void DrawInRevitView()
		{
			if (this.m_grid == null)
			{
				return;
			}
			XYZ move = null;
			if (this.CreateView(ref move) == ViewSelectResult.VSR_Cancel)
			{
				return;
			}
			this.GRID_SCALE = (double)this.m_doc.ActiveView.Scale;
			this.TEXT_SCALE = 1.0 / this.GRID_SCALE;
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			this.GetGridRealRowCol(ref num, ref num2, ref num3, ref num4);
			if (num == 0 && num2 == 0 && num3 == 0 && num4 == 0)
			{
				YJKMessageBox.Show("表格内容为空");
				return;
			}
			if (num2 < this.m_grid.Rows - 1)
			{
				this.m_grid.Range(num2 + 1, 0, this.m_grid.Rows - 1, 0).DeleteByRow();
			}
			this.m_grid.Range(1, 0, num - 1, 0).DeleteByRow();
			if (num4 < this.m_grid.Cols - 1)
			{
				this.m_grid.Range(0, num4 + 1, 0, this.m_grid.Cols - 1).DeleteByCol();
			}
			this.m_grid.Range(0, 1, 0, num3 - 1).DeleteByCol();
			this.m_GridLineInfoH = new GridLineInfo[this.m_grid.Rows, this.m_grid.Cols - 1];
			this.m_GridLineInfoV = new GridLineInfo[this.m_grid.Rows - 1, this.m_grid.Cols];
			if (!this.GetGridDrawInfo())
			{
				return;
			}
			if (this.m_GridLineInfoH == null || this.m_GridLineInfoV == null || this.m_GridLineInfoH.Length <= 0 || this.m_GridLineInfoV.Length <= 0)
			{
				return;
			}
			this.GetLineStyle(ref this.m_GridLineStyleOut, ref this.m_GridLineStyleInner);
			if (this.m_GridLineStyleOut == null || this.m_GridLineStyleInner == null)
			{
				return;
			}
			this.DrawGridLine();
			if (this.m_ptPos == null && !this.DragJig(ref move))
			{
				return;
			}
			this.RealDrawing(move, false);
		}

		private ViewSelectResult CreateView(ref XYZ ptPos)
		{
			if (this.m_GridName == "")
			{
				this.m_GridName = "表格工具";
			}
			if (this.m_IfCreateNewView == CREATENEWVIEW.NONE)
			{
				if (this.m_ptPos == null)
				{
					return TableInterface.GridDrawView(this.m_cmdData, this.m_GridName);
				}
				ptPos = this.m_ptPos;
			}
			else if (this.m_IfCreateNewView == CREATENEWVIEW.NEWVIEW)
			{
				TableInterface.GridNewDrawView(this.m_cmdData, this.m_GridName);
			}
			else
			{
				if (this.m_IfCreateNewView == CREATENEWVIEW.CURRENT)
				{
					ptPos = null;
					return ViewSelectResult.VSR_Current;
				}
				return TableInterface.GridDrawView(this.m_cmdData, this.m_GridName);
			}
			return ViewSelectResult.VSR_UserSelect;
		}

		private void DrawGridLine()
		{
			if (this.m_GridLineInfoH.Length <= 0 || this.m_GridLineInfoV.Length <= 0)
			{
				return;
			}
			XYZ xyz = this.m_ptBase;
			int length = this.m_GridLineInfoH.GetLength(0);
			int length2 = this.m_GridLineInfoH.GetLength(1);
			for (int i = 0; i < length; i++)
			{
				if (i != 0)
				{
					xyz -= XYZ.BasisY * this.m_GridLineInfoV[i - 1, 0].LineLength;
				}
				XYZ xyz2 = xyz;
				XYZ xyz3 = xyz2;
				for (int j = 0; j < length2; j++)
				{
					GridLineInfo gridLineInfo = this.m_GridLineInfoH[i, j];
					if (!gridLineInfo.DrawLine)
					{
						this.m_GridLine.Add(new JigEdgeInfoEx(new JigEdgeInfo(xyz2, xyz3, 0.0), false));
						xyz3 += XYZ.BasisX * gridLineInfo.LineLength;
						xyz2 = xyz3;
					}
					else
					{
						xyz3 += XYZ.BasisX * gridLineInfo.LineLength;
						if (j == length2 - 1 && xyz2.DistanceTo(xyz3) > 0.0)
						{
							if (i == 0 || i == length - 1)
							{
								this.m_GridLine.Add(new JigEdgeInfoEx(new JigEdgeInfo(xyz2, xyz3, 0.0), true));
							}
							else
							{
								this.m_GridLine.Add(new JigEdgeInfoEx(new JigEdgeInfo(xyz2, xyz3, 0.0), false));
							}
						}
					}
				}
			}
			xyz = this.m_ptBase;
			int length3 = this.m_GridLineInfoV.GetLength(0);
			int length4 = this.m_GridLineInfoV.GetLength(1);
			for (int k = 0; k < length4; k++)
			{
				if (k != 0)
				{
					xyz += XYZ.BasisX * this.m_GridLineInfoH[0, k - 1].LineLength;
				}
				XYZ xyz4 = xyz;
				XYZ xyz5 = xyz4;
				for (int l = 0; l < length3; l++)
				{
					GridLineInfo gridLineInfo2 = this.m_GridLineInfoV[l, k];
					if (!gridLineInfo2.DrawLine)
					{
						this.m_GridLine.Add(new JigEdgeInfoEx(new JigEdgeInfo(xyz4, xyz5, 0.0), false));
						xyz5 -= XYZ.BasisY * gridLineInfo2.LineLength;
						xyz4 = xyz5;
					}
					else
					{
						xyz5 -= XYZ.BasisY * gridLineInfo2.LineLength;
						if (l == length3 - 1 && xyz4.DistanceTo(xyz5) > 0.0)
						{
							if (k == 0 || k == length4 - 1)
							{
								this.m_GridLine.Add(new JigEdgeInfoEx(new JigEdgeInfo(xyz4, xyz5, 0.0), true));
							}
							else
							{
								this.m_GridLine.Add(new JigEdgeInfoEx(new JigEdgeInfo(xyz4, xyz5, 0.0), false));
							}
						}
					}
				}
			}
		}

		private double UnitTransform(short value)
		{
			return (double)value / this.m_dpiY * 0.08333;
		}

		private double UnitTransform(float value)
		{
			return (double)value / this.m_dpiY * 0.08333;
		}

		private bool DragJig(ref XYZ ptPos)
		{
			List<JigEdgeInfo> list = new List<JigEdgeInfo>();
			foreach (JigEdgeInfoEx jigEdgeInfoEx in this.m_GridLine)
			{
				list.Add(jigEdgeInfoEx.jigEdgeInfo);
			}
			try
			{
				if (!DragCurveJigInterface.GetInsertPosition(this.m_cmdData, list, false, XYZ.Zero, ref ptPos))
				{
					return false;
				}
			}
			catch (Exception)
			{
				return false;
			}
			return true;
		}

		private bool RealDrawing(XYZ move, bool isChangeIcon = false)
		{
			Category category = this.m_doc.Settings.Categories.get_Item(BuiltInCategory.OST_RasterImages);
			if (!this.m_doc.ActiveView.GetYJKVisibility(category))
			{
				Transaction transaction = new Transaction(this.m_doc, "Showing");
				transaction.Start();
				try
				{
					this.m_doc.ActiveView.SetYJKVisibility(category, true);
					transaction.Commit();
				}
				catch
				{
					transaction.RollBack();
				}
			}
			Transaction transaction2 = new Transaction(this.m_doc);
			bool result;
			try
			{
				Group group = null;
				transaction2.Start("drawing");
				this.m_cmdData.Application.Application.FailuresProcessing += this.OnFailuresProcessing;
                Autodesk.Revit.ApplicationServices.Application application = this.m_cmdData.Application.Application;
				Transform moveTransf = RevitVersionFuncs.CreateTranslation(move);
				this.DrawGridLine(this.m_GridLine, this.m_GridLineStyleOut, this.m_GridLineStyleInner, moveTransf, application, isChangeIcon);
				this.DrawGridText(moveTransf, isChangeIcon);
				this.DrawGridImg(moveTransf);
				if (this.m_elemSet.Size > 0)
				{
					group = this.m_doc.CreatYJKGroup(this.m_elemSet);
					if (group != null)
					{
						GridExtendedData.WriteGridExtendedData(move, ref group, this.m_RowHeightEx, this.m_ColWidthEx, this.m_CellExtendInfo, this.m_RefreshData);
					}
				}
				transaction2.Commit();
				if (group != null)
				{
					Transaction transaction3 = new Transaction(this.m_doc, "MoveGroup");
					try
					{
						transaction3.Start();
						ElementTransformUtils.MoveElement(this.m_doc, group.Id, XYZ.BasisX * 0.0001);
						transaction3.Commit();
					}
					catch
					{
						transaction3.RollBack();
					}
				}
				result = true;
			}
			catch (Exception)
			{
				transaction2.RollBack();
				result = false;
			}
			return result;
		}

		private void OnFailuresProcessing(object sender, FailuresProcessingEventArgs e)
		{
			e.GetFailuresAccessor().DeleteAllWarnings();
		}

		private void DrawGridLine(List<JigEdgeInfoEx> lstInfos, GraphicsStyle lineStyleOut, GraphicsStyle lineStyleInner, Transform moveTransf, Autodesk.Revit.ApplicationServices.Application app, bool isChangeIcon = false)
		{
			if (GridToolExportImportRevit._hWndRevit == null)
			{
                GridToolExportImportRevit._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			ProgressBarForm progressBarForm = new ProgressBarForm(lstInfos.Count, "正在绘制表格", ProgressBarStyle.Blocks, true, false);
			progressBarForm.Show(GridToolExportImportRevit._hWndRevit);
			foreach (JigEdgeInfoEx jigEdgeInfoEx in lstInfos)
			{
				progressBarForm.RefreshProgressBar();
				if (progressBarForm.m_stopTag)
				{
					break;
				}
				JigEdgeInfo jigEdgeInfo = jigEdgeInfoEx.jigEdgeInfo;
				jigEdgeInfo.TransformSelf(moveTransf);
				Curve curve = jigEdgeInfo.ConvertTo(app);
				DetailCurve detailCurve;
				if (jigEdgeInfoEx.Border)
				{
					detailCurve = this.DrawCurve(curve, lineStyleOut);
				}
				else
				{
					detailCurve = this.DrawCurve(curve, lineStyleInner);
				}
				if (detailCurve != null)
				{
					this.m_elemSet.Insert(detailCurve);
				}
			}
		}

		private DetailCurve DrawCurve(Curve curve, GraphicsStyle lineStyle)
		{
			DetailCurve result;
			try
			{
				Autodesk.Revit.DB.View activeView = this.m_cmdData.Application.ActiveUIDocument.ActiveView;
				DetailCurve detailCurve = this.m_doc.Create.NewDetailCurve(activeView, curve);
				if (detailCurve != null)
				{
					detailCurve.LineStyle = lineStyle;
				}
				result = detailCurve;
			}
			catch (Exception)
			{
				result = null;
			}
			return result;
		}

		private void DrawGridText(Transform moveTransf, bool isChangeIcon = false)
		{
			if (this.m_GridText.Count <= 0)
			{
				return;
			}
			if (GridToolExportImportRevit._hWndRevit == null)
			{
                GridToolExportImportRevit._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			ProgressBarForm progressBarForm = new ProgressBarForm(this.m_GridText.Count, "正在绘制表格", ProgressBarStyle.Blocks, true, false);
			progressBarForm.Show(GridToolExportImportRevit._hWndRevit);
			foreach (JigTextInfoEx jigTextInfoEx in this.m_GridText)
			{
				progressBarForm.RefreshProgressBar();
				if (progressBarForm.m_stopTag)
				{
					break;
				}
				JigTextInfo jigTextInfo = jigTextInfoEx.JigTextInfo;
				jigTextInfo.TransformSelf(moveTransf, false);
				if (jigTextInfo.StrText.CompareTo("") != 0)
				{
					try
					{
						XYZ upVec = Geometry.RotateTo(jigTextInfo.BaseVec, Math.PI*.5, XYZ.BasisZ);
						TextNote textNode = this.m_doc.GetTextNode(this.m_doc.ActiveView, jigTextInfo.Origin, jigTextInfo.BaseVec, upVec, jigTextInfo.LineWidth, jigTextInfo.TextAlign, jigTextInfo.StrText);
						textNode.TextNoteType = jigTextInfo.theTextNoteType;
						if (textNode != null)
						{
							this.m_elemSet.Insert(textNode);
							this.SetExtendedData(jigTextInfoEx.Row, jigTextInfoEx.Col, textNode.Id);
						}
					}
					catch (Exception)
					{
					}
				}
			}
		}

		private void SetExtendedData(int row, int col, ElementId id)
		{
			foreach (CellExtendedData cellExtendedData in this.m_CellExtendInfo)
			{
				if (cellExtendedData.FirstRow == row && cellExtendedData.FirstCol == col)
				{
					cellExtendedData.Id = id;
					break;
				}
			}
		}

		private void DrawGridImg(Transform moveTransf)
		{
			if (this.m_GridImage.Count <= 0)
			{
				return;
			}
			if (GridToolExportImportRevit._hWndRevit == null)
			{
				GridToolExportImportRevit._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			ProgressBarForm progressBarForm = new ProgressBarForm(this.m_GridImage.Count, "正在绘制表格", ProgressBarStyle.Blocks, true, false);
			progressBarForm.Show(GridToolExportImportRevit._hWndRevit);
			for (int i = 0; i < this.m_GridImage.Count; i++)
			{
				progressBarForm.RefreshProgressBar();
				if (progressBarForm.m_stopTag)
				{
					return;
				}
				GridImgInfo gridImgInfo = this.m_GridImage[i];
				string text = gridImgInfo.ImageKey;
				FlexCell.Image image = this.m_grid.Images.Item(text);
				if (string.IsNullOrEmpty(Path.GetExtension(text)))
				{
					text += ".jpg";
				}
				string text2 = Environment.GetEnvironmentVariable("TEMP");
				text2 = text2 + "\\" + text;
				image.SaveAs(text2, this.GetImageFormat(text));
				ImageImportOptions imageImportOptions = new ImageImportOptions();
				imageImportOptions.Placement = 0;
				imageImportOptions.RefPoint = moveTransf.OfPoint(gridImgInfo.Position);
				Element element = null;
				if (this.m_doc.Import(text2, imageImportOptions, this.m_doc.ActiveView, out element) && element != null)
				{
					element.GetParameter(BuiltInParameter.RASTER_MAINTAIN_ASPECT_RATIO).Set(0);
					element.GetParameter(BuiltInParameter.RASTER_SHEETWIDTH).Set(gridImgInfo.Width);
					element.GetParameter(BuiltInParameter.RASTER_SHEETHEIGHT).Set(gridImgInfo.Height);
				}
				if (element != null)
				{
					this.m_elemSet.Insert(element);
					this.SetExtendedData(gridImgInfo.Row, gridImgInfo.Col, element.Id);
				}
				File.Delete(text2);
			}
		}

		private ImageFormat GetImageFormat(string strImgKey)
		{
			string extension = Path.GetExtension(strImgKey);
			if (extension.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || extension.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
			{
				return ImageFormat.Jpeg;
			}
			if (extension.Equals(".png", StringComparison.OrdinalIgnoreCase))
			{
				return ImageFormat.Png;
			}
			if (extension.Equals(".gif", StringComparison.OrdinalIgnoreCase))
			{
				return ImageFormat.Gif;
			}
			if (extension.Equals(".icon", StringComparison.OrdinalIgnoreCase) || extension.Equals(".ico", StringComparison.OrdinalIgnoreCase))
			{
				return ImageFormat.Icon;
			}
			if (extension.Equals(".tif", StringComparison.OrdinalIgnoreCase) || extension.Equals(".tiff", StringComparison.OrdinalIgnoreCase))
			{
				return ImageFormat.Tiff;
			}
			if (extension.Equals(".bmp", StringComparison.OrdinalIgnoreCase))
			{
				return ImageFormat.Bmp;
			}
			return ImageFormat.Jpeg;
		}

		public void SetRefreshData(Autodesk.Revit.DB.View curView, int nStaticType, List<ViewPlan> lstViewPlan, List<StandardLevel> lstStandardLevel, List<SelectAreaCurve> lstSelAreaCurve, GridSetCommonInfo gridSetInfo)
		{
			this.m_RefreshData.DocName = this.m_doc.Title;
			foreach (ViewPlan viewPlan in lstViewPlan)
			{
				this.m_RefreshData.ViewPlans.Add(viewPlan.Id);
			}
			this.m_RefreshData.StandardFloor = lstStandardLevel;
			this.m_RefreshData.SelAreaCurve = lstSelAreaCurve;
			this.m_RefreshData.SelCurViewPlan = curView.Id;
			this.m_RefreshData.StatisticType = nStaticType;
			this.m_RefreshData.GridSetInfo.LinkFile = gridSetInfo.LinkFile;
			this.m_RefreshData.GridSetInfo.TemplateName = gridSetInfo.TemplateName;
			this.m_RefreshData.GridSetInfo.GridName = gridSetInfo.GridName;
			this.m_RefreshData.GridSetInfo.LstColumnWidth = gridSetInfo.LstColumnWidth;
			this.m_RefreshData.GridSetInfo.FontSize = gridSetInfo.FontSize;
			this.m_RefreshData.GridSetInfo.TitleFontSize = gridSetInfo.TitleFontSize;
			this.m_RefreshData.GridSetInfo.FontName = gridSetInfo.FontName;
			this.m_RefreshData.GridSetInfo.LineWidthOut = gridSetInfo.LineWidthOut;
			this.m_RefreshData.GridSetInfo.LineWidthInner = gridSetInfo.LineWidthInner;
			this.m_RefreshData.GridSetInfo.HeadRows = gridSetInfo.HeadRows;
			this.m_RefreshData.GridSetInfo.TitleDown = gridSetInfo.TitleDown;
		}

		public void SetRefreshData(GridDataRefresh dataRrefresh)
		{
			this.m_RefreshData = dataRrefresh;
		}

        public void AbstractGridFromRevit(ref FlexCell.Grid grid, List<short> GridRows, List<short> GridCols, List<CellExtendedData> cellExtendedInfo)
		{
			int count = GridRows.Count;
			int count2 = GridCols.Count;
			grid.AutoRedraw = false;
			grid.DisplayRowNumber = true;
			grid.ShowResizeTip = true;
			grid.Rows = count + 1;
			grid.Cols = count2 + 1;
			for (int i = 1; i <= count; i++)
			{
				grid.Row(i).Height = GridRows[i - 1];
			}
			for (int j = 1; j <= count2; j++)
			{
				grid.Column(j).Width = GridCols[j - 1];
				grid.Cell(0, j).Text = j.ToString();
			}
			foreach (CellExtendedData cellExtendedData in cellExtendedInfo)
			{
				short num = 0;
				short num2 = 0;
				if (cellExtendedData.FirstRow != cellExtendedData.LastRow || cellExtendedData.FirstCol != cellExtendedData.LastCol)
				{
					grid.Range(cellExtendedData.FirstRow, cellExtendedData.FirstCol, cellExtendedData.LastRow, cellExtendedData.LastCol).Merge();
					for (int k = cellExtendedData.FirstRow; k <= cellExtendedData.LastRow; k++)
					{
						num += GridRows[k - 1];
					}
					for (int l = cellExtendedData.FirstCol; l <= cellExtendedData.LastCol; l++)
					{
						num2 += GridCols[l - 1];
					}
				}
				else
				{
					num = GridRows[cellExtendedData.FirstRow - 1];
					num2 = GridCols[cellExtendedData.FirstCol - 1];
				}
				Cell cell = grid.Cell(cellExtendedData.FirstRow, cellExtendedData.FirstCol);
				this.GetCellBorderDataEx(ref cell, cellExtendedData.BorderStyle);
				if (!(cellExtendedData.Id == null))
				{
					Element element = this.m_doc.GetElement(cellExtendedData.Id);
					if (element != null)
					{
						int integerValue = element.Category.Id.IntegerValue;
						if (integerValue == -2000300)
						{
							TextNote textNote = element as TextNote;
							TextNoteType textNoteType = textNote.TextNoteType;
							cell.Text = textNote.Text;
							cell.FontName = textNoteType.GetParameter(BuiltInParameter.TEXT_FONT).AsString();
							double num3 = textNoteType.GetParameter(BuiltInParameter.TEXT_SIZE).AsDouble();
							num3 = num3 * 14.0 * 72.0;
							cell.FontSize = Convert.ToSingle(num3);
							cell.FontBold = (textNoteType.GetParameter(BuiltInParameter.TEXT_STYLE_BOLD).AsInteger() == 1);
							cell.FontItalic = (textNoteType.GetParameter(BuiltInParameter.TEXT_STYLE_ITALIC).AsInteger() == 1);
							cell.FontUnderline = (textNoteType.GetParameter(BuiltInParameter.TEXT_STYLE_UNDERLINE).AsInteger() == 1);
							int color = textNoteType.GetParameter(BuiltInParameter.LINE_COLOR).AsInteger();
							cell.ForeColor = this.ParseColor(color);
							if (textNote.BaseDirection.AngleTo(XYZ.BasisX) > 0.001)
							{
								cell.Orientation = TextOrientationEnum.Vertical;
							}
							this.SetTextAlignment(ref cell, textNote);
						}
						else if (integerValue == -2000560)
						{
							Bitmap imageFromRevit = RevitDocumentExtension.GetImageFromRevit(this.m_doc, element);
							if (imageFromRevit != null)
							{
								string name = element.Name;
								string text = Environment.GetEnvironmentVariable("TEMP") + "\\" + name;
								imageFromRevit.Save(text, this.GetImageFormat(name));
								grid.Images.Add(text, name);
								cell.SetImage(name);
								this.SetImgAlignment(ref cell, num, num2, element, imageFromRevit);
								File.Delete(text);
							}
						}
					}
				}
			}
			grid.AutoRedraw = true;
			grid.Refresh();
		}

		private System.Drawing.Color ParseColor(int color)
		{
			int red = color & 255;
			int green = (color & 65280) >> 8;
			int blue = (color & 16711680) >> 16;
			return System.Drawing.Color.FromArgb(red, green, blue);
		}

		private void SetTextAlignment(ref Cell cell, TextNote text)
		{
			if (text == null)
			{
				return;
			}
			string a = text.GetParameter(BuiltInParameter.TEXT_ALIGN_HORZ).AsValueString();
			string a2 = text.GetParameter(BuiltInParameter.TEXT_ALIGN_VERT).AsValueString();
			if (a == "左" && a2 == "顶")
			{
				cell.Alignment = AlignmentEnum.LeftTop;
				return;
			}
			if (a == "左" && a2 == "中部")
			{
				cell.Alignment = AlignmentEnum.LeftCenter;
				return;
			}
			if (a == "左" && a2 == "底")
			{
				cell.Alignment = AlignmentEnum.LeftBottom;
				return;
			}
			if (a == "中心线" && a2 == "顶")
			{
				cell.Alignment = AlignmentEnum.CenterTop;
				return;
			}
			if (a == "中心线" && a2 == "中部")
			{
				cell.Alignment = AlignmentEnum.CenterCenter;
				return;
			}
			if (a == "中心线" && a2 == "底")
			{
				cell.Alignment = AlignmentEnum.CenterBottom;
				return;
			}
			if (a == "右" && a2 == "顶")
			{
				cell.Alignment = AlignmentEnum.RightTop;
				return;
			}
			if (a == "右" && a2 == "中部")
			{
				cell.Alignment = AlignmentEnum.RightCenter;
				return;
			}
			if (a == "右" && a2 == "底")
			{
				cell.Alignment = AlignmentEnum.RightBottom;
				return;
			}
			cell.Alignment = AlignmentEnum.CenterCenter;
		}

		private void SetImgAlignment(ref Cell cell, short rowHeigth, short colWidth, Element elemImg, Bitmap bmp)
		{
			if (cell == null || elemImg == null)
			{
				return;
			}
			double num = (double)bmp.Height;
			double num2 = (double)bmp.Width;
			double num3 = elemImg.GetParameter(BuiltInParameter.RASTER_SHEETHEIGHT).AsDouble();
			double num4 = elemImg.GetParameter(BuiltInParameter.RASTER_SHEETWIDTH).AsDouble();
			if (num / num2 - num3 / num4 < 0.01 && num / num2 - num3 / num4 > 0.01)
			{
				cell.Alignment = AlignmentEnum.CenterCenter;
				return;
			}
			double num5 = this.UnitTransform(rowHeigth) * this.GRID_SCALE;
			double num6 = this.UnitTransform(colWidth) * this.GRID_SCALE;
			if (object.Equals(num5, num3) && object.Equals(num6, num4))
			{
				cell.Alignment = AlignmentEnum.GeneralGeneral;
				return;
			}
			if (Geometry.GreaterThan(num5, num3))
			{
				cell.Alignment = AlignmentEnum.CenterGeneral;
				return;
			}
			cell.Alignment = AlignmentEnum.GeneralCenter;
		}

		private void SetCellBorderDataEx(Cell cell, ref CellExtendedData cellDataEx)
		{
			if (cell == null)
			{
				return;
			}
			string text = "";
			LineStyleEnum lineStyleEnum = cell.get_Border(EdgeEnum.Top);
			if (lineStyleEnum == LineStyleEnum.Thin)
			{
				text += "/0";
			}
			else if (lineStyleEnum == LineStyleEnum.Thick)
			{
				text += "/1";
			}
			lineStyleEnum = cell.get_Border(EdgeEnum.Bottom);
			if (lineStyleEnum == LineStyleEnum.Thin)
			{
				text += "/2";
			}
			else if (lineStyleEnum == LineStyleEnum.Thick)
			{
				text += "/3";
			}
			lineStyleEnum = cell.get_Border(EdgeEnum.Left);
			if (lineStyleEnum == LineStyleEnum.Thin)
			{
				text += "/4";
			}
			else if (lineStyleEnum == LineStyleEnum.Thick)
			{
				text += "/5";
			}
			lineStyleEnum = cell.get_Border(EdgeEnum.Right);
			if (lineStyleEnum == LineStyleEnum.Thin)
			{
				text += "/6";
			}
			else if (lineStyleEnum == LineStyleEnum.Thick)
			{
				text += "/7";
			}
			if (cell.get_Border(EdgeEnum.DiagonalUp) != LineStyleEnum.None)
			{
				text += "/8";
			}
			if (cell.get_Border(EdgeEnum.DiagonalDown) != LineStyleEnum.None)
			{
				text += "/9";
			}
			cellDataEx.BorderStyle = text;
		}

		private void GetCellBorderDataEx(ref Cell cell, string strBorderStyle)
		{
			foreach (string value in strBorderStyle.Split(new char[]
			{
				'/'
			}))
			{
				if (!string.IsNullOrEmpty(value))
				{
					switch (Convert.ToInt16(value))
					{
					case 0:
						cell.set_Border(EdgeEnum.Top, LineStyleEnum.Thin);
						break;
					case 1:
						cell.set_Border(EdgeEnum.Top, LineStyleEnum.Thick);
						break;
					case 2:
						cell.set_Border(EdgeEnum.Bottom, LineStyleEnum.Thin);
						break;
					case 3:
						cell.set_Border(EdgeEnum.Bottom, LineStyleEnum.Thick);
						break;
					case 4:
						cell.set_Border(EdgeEnum.Left, LineStyleEnum.Thin);
						break;
					case 5:
						cell.set_Border(EdgeEnum.Left, LineStyleEnum.Thick);
						break;
					case 6:
						cell.set_Border(EdgeEnum.Right, LineStyleEnum.Thin);
						break;
					case 7:
						cell.set_Border(EdgeEnum.Right, LineStyleEnum.Thick);
						break;
					case 8:
						cell.set_Border(EdgeEnum.DiagonalUp, LineStyleEnum.Thin);
						break;
					case 9:
						cell.set_Border(EdgeEnum.DiagonalDown, LineStyleEnum.Thin);
						break;
					}
				}
			}
		}

		private double GRID_SCALE = 100.0;

		private double TEXT_SCALE = 0.01;

		private ExternalCommandData m_cmdData;

		private Document m_doc;

        private FlexCell.Grid m_grid;

		private double m_dpiX;

		private double m_dpiY;

		private XYZ m_ptBase = XYZ.Zero;

		private GridLineInfo[,] m_GridLineInfoH;

		private GridLineInfo[,] m_GridLineInfoV;

		private List<JigEdgeInfoEx> m_GridLine = new List<JigEdgeInfoEx>();

		private GraphicsStyle m_GridLineStyleOut;

		private GraphicsStyle m_GridLineStyleInner;

		private const string m_strGridLineStyleOut = "GridLineOut";

		private const string m_strGridLineStyleInner = "GridLineInner";

        private Autodesk.Revit.DB.Color m_GridLineColor = new Autodesk.Revit.DB.Color(0, 0, 0);

		private string m_GridName = "";

		private List<JigTextInfoEx> m_GridText = new List<JigTextInfoEx>();

		private List<GridImgInfo> m_GridImage = new List<GridImgInfo>();

		private ElementSet m_elemSet = new ElementSet();

		private XYZ m_ptPos;

		private List<short> m_RowHeightEx = new List<short>();

		private List<short> m_ColWidthEx = new List<short>();

		private List<CellExtendedData> m_CellExtendInfo = new List<CellExtendedData>();

		private int m_LineWidthOut = 7;

		private int m_LineWidthInner = 2;

		public static WindowHandle _hWndRevit;

		private CREATENEWVIEW m_IfCreateNewView = CREATENEWVIEW.NONE;

		private GridDataRefresh m_RefreshData = new GridDataRefresh();

		private int m_nVersionNumber;

		public bool m_bIsSplitTable;

		private Dictionary<Cell, int> m_dicRowNumbers = new Dictionary<Cell, int>();

		private Dictionary<Cell, double> m_dicOneRowTextNumbers = new Dictionary<Cell, double>();

		private Dictionary<int, short> m_dicRowHigh = new Dictionary<int, short>();

		private Dictionary<int, short> m_dicColWidth = new Dictionary<int, short>();
	}
}
